package org.university.repository;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import org.university.entity.Course;
import org.university.entity.Enrollment;

import java.util.List;

@Repository
public interface EnrollmentRepository extends JpaRepository<Enrollment, Integer> {

    Page<Enrollment> findByDeletedFalse(Pageable pageable);

    /**
     *
     * 从enrollment表里获取当前id的学生的所有选课信息条目
     * 再根据teaching_class表找到对应的course_id
     * 根据course_id从course表返回对应信息条目
     * 最后整合所有返回符合要求的course条目
     *
     * @param studentId
     * @return
     */
    @Query("SELECT c FROM Course c " +
            "JOIN TeachingClass tc ON c.courseId = tc.courseId " +
            "JOIN Enrollment e ON tc.classId = e.teachingClass.classId " +
            "WHERE e.studentId = :studentId AND e.deleted = 0")
    List<Course> findCoursesByStudentId(@Param("studentId") String studentId);

    @Query("SELECT COUNT(e) > 0 FROM Enrollment e " +
            "JOIN e.teachingClass tc " + // 使用关联属性
            "WHERE e.studentId = :studentId " +
            "AND tc.courseId = :courseId " +
            "AND e.deleted = 0")
    boolean existsByStudentIdAndCourseId(
            @Param("studentId") String studentId,
            @Param("courseId") String courseId
    );

    @Query("SELECT e FROM Enrollment e " +
            "JOIN e.teachingClass tc " +
            "WHERE e.studentId = :studentId " +
            "AND tc.courseId = :courseId " +
            "AND e.teachingClass.classId = tc.classId " +
            "AND e.deleted = 0")
    Enrollment findByStudentIdAndCourseId(@Param("studentId") String studentId, @Param("courseId") String courseId);
}

